<template>
  <div v-infinite-scroll="loadMore" infinite-scroll-distance="10"  infinite-scroll-disabled="loading">
        <slot :list="list"></slot>
        <slot name="data-empty" v-if="hasnomore && list.length==0">
            <div class="list-data-isempty">
                没有找到相关记录~
            </div>
        </slot>
        <slot name="loading">
            <div v-show="canload && loading && !hasnomore" class="list-loading">       
          <div class="flex">
            <div>
              <mt-spinner type="fading-circle" color="#222" :size="18"></mt-spinner>
              </div>   
              <div class="list-loading-txt">加载中...</div>
          </div>
        </div>
        </slot>
        <slot name="hasnomore">
            <div v-show="hasnomore && list.length > 0" class="list-loading nomore-txt">
                没有更多了...
            </div>
        </slot>        
    </div>
</template>
<script>
export default {
  props: {
    url: {
      type: String
    },
    pagination: {
      type: Boolean,
      default: true
    },
    autoload: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      list: [],
      canload: true,
      hasnomore: false,
      loading: false
    };
  },
  created() {
    this.p = 0;
    this.loading = !this.autoload;
    this.canload = this.autoload;
    this.params = {};
  },
  methods: {
    clearParams() {
      this.params = {};
      return this;
    },
    addParam(field, value) {
      this.params[field] = value;
      return this;
    },
    setParams(params){
      this.params = params;
      return this;
    },
    refresh() {
      this.p = 0;
      this.loading = false;
      this.canload = true;
      this.hasnomore = false;
      this.list = [];
      this.loadMore();
    },
    removeItem(id,idField){
      idField = idField || 'id';
      this.list.forEach((el,index)=>{
        if(el[idField] == id){
          this.list.splice(index,1);
        }
      })
    },
    loadMore() {
      if (this.p >= 1 && !this.pagination) {
        return;
      }
      console.log("loading more");
      if (this.loading) {
        return;
      }
      this.p++;
      this.loading = true;
      this.$get(this.url, { p: this.p, ...this.params }).then(data => {
        data = data || [];
        if (data.length < 10) {
          this.hasnomore = true;
        } else {
          this.loading = false;
        }
        this.list.push(...data);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.nomore-txt {
  font-size: 0.3rem;
  color: #999;
  padding-bottom: 0.6rem;
}
</style>

